// src/store/template.js
import { defineStore } from 'pinia'
import { templateApi, avatarApi, voiceApi } from '@/api/template'
import { ElMessage, ElNotification } from 'element-plus'

export const useTemplateStore = defineStore('template', {
    state: () => ({
        // 模板列表相关
        templates: [],
        total: 0,
        loading: false,
        syncLoading: false,

        // 生成相关
        generating: false,
        checkingStatus: false,

        // 视频记录
        videoRecord: {
            id: '',
            status: 'PENDING',
            videoUrl: '',
            errorMessage: ''
        },

        // 选中的模板
        selectedTemplate: {},
        templateVariables: {},

        // 配置和角色
        configList: [],
        avatarList: [],
        voiceList: [],

        // 状态检查定时器
        statusCheckTimer: null
    }),

    getters: {
        hasVariables: (state) => {
            return state.templateVariables &&
                Object.keys(state.templateVariables).length > 0
        },

        statusStep: (state) => {
            if (state.videoRecord.status === 'COMPLETED') return 3
            if (state.videoRecord.status === 'PROCESSING') return 2
            if (state.videoRecord.status === 'FAILED') return 2
            return 1
        },

        statusText: (state) => {
            const statusMap = {
                'PENDING': '等待处理',
                'PROCESSING': '视频生成中',
                'COMPLETED': '生成完成',
                'FAILED': '生成失败'
            }
            return statusMap[state.videoRecord.status] || '未知状态'
        }
    },

    actions: {
        // 获取模板列表
        async fetchTemplates(query) {
            this.loading = true
            try {
                const response = await templateApi.getTemplateList(query)
                if (response.code === 200) {
                    this.templates = response.data.records || []
                    this.total = response.data.total || 0
                } else {
                    ElMessage.error(response.msg || '获取模板列表失败')
                }
            } catch (error) {
                console.error('获取模板列表失败:', error)
                ElMessage.error('获取模板列表失败')
            } finally {
                this.loading = false
            }
        },

        // 同步模板
        async syncTemplates() {
            this.syncLoading = true
            try {
                const response = await templateApi.syncTemplates()
                if (response.data.code === 200) {
                    ElMessage.success(response.data.data || '同步成功')
                    return response.data.data
                } else {
                    ElMessage.error(response.data.msg || '同步失败')
                    throw new Error(response.data.msg || '同步失败')
                }
            } catch (error) {
                console.error('同步模板失败:', error)
                ElMessage.error('同步模板失败')
                throw error
            } finally {
                this.syncLoading = false
            }
        },

        // 选择模板
        async selectTemplate(template) {
            this.selectedTemplate = template

            // 解析模板变量
            try {
                if (template.variableConfig) {
                    this.templateVariables = JSON.parse(template.variableConfig)
                } else {
                    this.templateVariables = {}
                }

                // 加载配置和角色列表
                await this.fetchConfigsAndAvatars()

                return {
                    variables: this.templateVariables,
                    success: true
                }
            } catch (error) {
                console.error('解析模板变量失败:', error)
                ElMessage.error('解析模板变量失败')
                return {
                    success: false,
                    error: error.message
                }
            }
        },

        // 获取配置和角色列表
        async fetchConfigsAndAvatars() {
            try {
                const [configResponse, avatarResponse, voiceResponse] = await Promise.all([
                    avatarApi.getConfigList(),
                    avatarApi.getAvatarList(),
                    voiceApi.getVoiceList()
                ])

                if (configResponse.data.code === 200) {
                    this.configList = configResponse.data.data || []
                }

                if (avatarResponse.data.code === 200) {
                    this.avatarList = avatarResponse.data.data || []
                }

                if (voiceResponse.data.code === 200) {
                    this.voiceList = voiceResponse.data.data || []
                }

                return {
                    configs: this.configList,
                    avatars: this.avatarList,
                    voices: this.voiceList
                }
            } catch (error) {
                console.error('获取配置或角色列表失败:', error)
                ElMessage.error('获取配置或角色列表失败')
                throw error
            }
        },

        // 生成视频
        async generateVideo(payload) {
            this.generating = true

            try {
                const response = await templateApi.generateVideo(payload)

                if (response.data.code === 200) {
                    this.videoRecord = response.data.data

                    // 开始定时检查
                    this.startStatusCheck()

                    return {
                        success: true,
                        record: this.videoRecord
                    }
                } else {
                    ElMessage.error(response.data.msg || '生成视频失败')
                    throw new Error(response.data.msg || '生成视频失败')
                }
            } catch (error) {
                console.error('生成视频失败:', error)
                ElMessage.error(error.message || '生成视频失败')
                throw error
            } finally {
                this.generating = false
            }
        },

        // 开始状态检查
        startStatusCheck() {
            // 清除可能存在的旧定时器
            if (this.statusCheckTimer) {
                clearInterval(this.statusCheckTimer)
            }

            // 创建新的定时器，每5秒检查一次
            this.statusCheckTimer = setInterval(() => {
                // 如果已完成或失败，停止检查
                if (this.videoRecord.status === 'COMPLETED' || this.videoRecord.status === 'FAILED') {
                    clearInterval(this.statusCheckTimer)
                    return
                }

                this.checkVideoStatus()
            }, 5000)

            // 立即检查一次
            this.checkVideoStatus()
        },

        // 检查视频状态
        async checkVideoStatus() {
            if (!this.videoRecord.id) return

            this.checkingStatus = true
            try {
                const response = await templateApi.checkVideoStatus(this.videoRecord.id)

                if (response.data.code === 200) {
                    this.videoRecord = response.data.data

                    // 如果视频生成完成，显示通知
                    if (this.videoRecord.status === 'COMPLETED') {
                        ElNotification({
                            title: '视频生成完成',
                            message: '您的视频已生成完成，可以预览和下载',
                            type: 'success',
                            duration: 0
                        })
                    }

                    // 如果失败，显示通知
                    if (this.videoRecord.status === 'FAILED') {
                        ElNotification({
                            title: '视频生成失败',
                            message: this.videoRecord.errorMessage || '未知错误',
                            type: 'error',
                            duration: 0
                        })
                    }

                    return this.videoRecord
                }
            } catch (error) {
                console.error('检查视频状态失败:', error)
            } finally {
                this.checkingStatus = false
            }
        },

        // 重置状态
        resetVideoStatus() {
            this.videoRecord = {
                id: '',
                status: 'PENDING',
                videoUrl: '',
                errorMessage: ''
            }

            if (this.statusCheckTimer) {
                clearInterval(this.statusCheckTimer)
                this.statusCheckTimer = null
            }
        }
    }
})